from flask import Blueprint, request, jsonify, current_app
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
import requests
from app.models.user import User
from main import db
from datetime import datetime

user_bp = Blueprint("user", __name__)


@user_bp.route("/wx-login", methods=["POST"])
def wx_login():
    data = request.get_json()
    code = data.get("code")
    userInfo = data["userInfo"]

    if not code:
        return jsonify({"error": "Missing code"}), 400

    # 从配置中获取小程序的appid和secret
    appid = current_app.config.get("WX_APPID")
    secret = current_app.config.get("WX_SECRET")

    if not appid or not secret:
        return jsonify({"error": "WeChat configuration missing"}), 500

    # 发送请求到微信服务器获取openid
    wx_url = f"https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={code}&grant_type=authorization_code"

    try:
        response = requests.get(wx_url)
        wx_data = response.json()

        if "errcode" in wx_data and wx_data["errcode"] != 0:
            return jsonify({"error": f"WeChat API error: {wx_data['errmsg']}"}), 400

        # 获取openid
        openid = wx_data.get("openid")
        if not openid:
            return jsonify({"error": "Failed to get openid from WeChat"}), 400

        # 查找或创建用户
        user = User.query.filter_by(openid=openid).first()

        if not user:
            user = User(openid=openid, username=userInfo["nickName"])
            db.session.add(user)
            db.session.commit()

        # 创建JWT令牌
        access_token = create_access_token(identity=user.id)
        return jsonify({"access_token": access_token, "user": user.to_dict()})

    except Exception as e:
        return jsonify({"error": f"Error connecting to WeChat API: {str(e)}"}), 500


@user_bp.route("/update-profile", methods=["PUT"])
@jwt_required()
def update_profile():
    user_id = get_jwt_identity()
    user = User.query.get_or_404(user_id)

    data = request.get_json()
    username = data.get("username")

    if username:
        user.username = username
        db.session.commit()

    return jsonify(user.to_dict())


@user_bp.route("/info", methods=["GET"])
@jwt_required()
def get_user_info():
    """获取当前登录用户的信息"""
    user_id = get_jwt_identity()
    user = User.query.get_or_404(user_id)

    return jsonify({"code": 200, "message": "获取成功", "data": user.to_dict()})


@user_bp.route("/list", methods=["GET"])
@jwt_required()
def get_user_list():
    """获取用户列表（管理员）"""
    user_id = get_jwt_identity()
    user = User.query.get_or_404(user_id)

    # 验证用户是否为管理员
    if not user.is_admin():
        return jsonify({"error": "没有管理员权限"}), 403

    # 查询参数
    page = request.args.get("page", 1, type=int)
    per_page = request.args.get("limit", 10, type=int)
    role = request.args.get("role", None, type=str)
    username = request.args.get("username", None, type=str)
    start_date = request.args.get("startDate", None, type=str)
    end_date = request.args.get("endDate", None, type=str)

    # 构建查询
    query = User.query

    # 按角色过滤
    if role:
        query = query.filter_by(role=role)

    # 按用户名搜索
    if username:
        query = query.filter(User.username.like(f"%{username}%"))

    # 按日期范围过滤
    if start_date:
        try:
            start_datetime = datetime.strptime(start_date, "%Y-%m-%d")
            query = query.filter(User.created_at >= start_datetime)
        except ValueError:
            pass

    if end_date:
        try:
            # 设置结束日期为当天的结束时间
            end_datetime = datetime.strptime(end_date, "%Y-%m-%d")
            end_datetime = end_datetime.replace(hour=23, minute=59, second=59)
            query = query.filter(User.created_at <= end_datetime)
        except ValueError:
            pass

    # 按创建时间降序排序
    query = query.order_by(User.created_at.desc())

    # 分页
    pagination = query.paginate(page=page, per_page=per_page)
    users = pagination.items

    return jsonify(
        {
            "code": 200,
            "message": "获取成功",
            "data": {
                "items": [user.to_dict() for user in users],
                "total": pagination.total,
                "page": page,
                "pages": pagination.pages,
                "per_page": per_page,
            },
        }
    )


@user_bp.route("/search", methods=["GET"])
@jwt_required()
def search_users():
    """搜索用户"""
    user_id = get_jwt_identity()
    user = User.query.get_or_404(user_id)

    # 验证用户是否为管理员
    if not user.is_admin():
        return jsonify({"error": "没有管理员权限"}), 403

    # 获取搜索参数
    username = request.args.get("username", None, type=str)

    # 构建查询
    query = User.query
    # 按用户名或openid搜索
    if username:
        query = query.filter(
            db.or_(
                User.username.like(f"%{username}%"),
                User.openid.like(f"%{username}%")
            )
        )

    # 按创建时间降序排序
    query = query.order_by(User.created_at.desc())

    # 获取结果
    users = query.all()

    return jsonify(
        {
            "code": 200,
            "message": "获取成功",
            "data": {"items": [user.to_dict() for user in users]},
        }
    )


@user_bp.route("/update-role/<int:user_id>", methods=["PUT"])
@jwt_required()
def update_user_role(user_id):
    """更新用户角色"""
    current_user_id = get_jwt_identity()
    current_user = User.query.get_or_404(current_user_id)

    # 验证当前用户是否为管理员
    if not current_user.is_admin():
        return jsonify({"error": "没有管理员权限"}), 403

    # 获取目标用户
    target_user = User.query.get_or_404(user_id)

    # 获取请求数据
    data = request.get_json()
    new_role = data.get("role")

    if not new_role:
        return jsonify({"error": "角色不能为空"}), 400

    # 验证角色值
    if new_role not in ["admin", "employee", "customer", "none"]:
        return jsonify({"error": "无效的角色值"}), 400

    # 更新用户角色
    target_user.role = new_role
    db.session.commit()

    return jsonify({"code": 200, "message": "更新成功", "data": target_user.to_dict()})
